package com.hrvsr.observer;

import java.util.concurrent.atomic.AtomicInteger;

public class State {

	public static final int NOT_INITED = -1;
	public static final int INITED = 0;
	public static final int RUNNING = 1;
	public static final int IDLE = 2;
	public static final int DONE = 3;

	public static String STATUS = "status";

	private String nodeId;

	private AtomicInteger status = new AtomicInteger(NOT_INITED);

	private AtomicInteger visitedRequests = new AtomicInteger(0);
	private AtomicInteger successRequests = new AtomicInteger(0);
	private AtomicInteger failureRequests = new AtomicInteger(0);

	private AtomicInteger downloaderThreads = new AtomicInteger(0);

	public void idle() {
		while (!status.compareAndSet(status.get(), IDLE))
			;
	}

	public void running() {
		while (!status.compareAndSet(status.get(), RUNNING))
			;
	}

	public void done() {
		while (!status.compareAndSet(status.get(), DONE))
			;
	}

	public void success() {
		successRequests.incrementAndGet();
		visitedRequests.incrementAndGet();
	}

	public void failure() {
		failureRequests.incrementAndGet();
		visitedRequests.incrementAndGet();
	}

	public void downloaderThreadsIncrease() {
		downloaderThreads.incrementAndGet();
	}

	public void downloaderThreadsdecrease() {
		downloaderThreads.decrementAndGet();
	}

	public int getDownloaderThreads() {
		return downloaderThreads.get();
	}

	public void setDownloaderThreadNum(int n) {
		while (true) {
			if (downloaderThreads.compareAndSet(downloaderThreads.get(), n))
				return;
		}
	}

	public int getStat() {
		return status.get();
	}

	public void setStat(int stat) {
		while (true) {
			if (status.compareAndSet(status.get(), stat))
				return;
		}
	}

	public String getNodeId() {
		return nodeId;
	}

	public void setNodeId(String nodeId) {
		this.nodeId = nodeId;
	}

	public State(String nodeId) {
		super();
		this.nodeId = nodeId;
	}

}
